<?php
namespace app\api\controller;

use app\BaseController;
use app\common\lib\pay\weixin\lib\database\WxPayUnifiedOrder;
use app\common\lib\pay\weixin\lib\WxPayNativePay;
use app\common\lib\phpqrcode\QRcode;
use app\common\business\Pay as Paybiz;
use app\common\lib\Show;
use think\facade\Cache;

class Pay extends BaseController
{
    public function demo() {
        $notify = new WxPayNativePay();
        $input = new WxPayUnifiedOrder();
        $input->SetBody("singwa商城");
        $input->SetAttach("欢迎选购");
        $input->SetOut_trade_no("singwa".date("YmdHis"));
        $input->SetTotal_fee("1");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 300));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://zzihou.xin:8080/api/index/index");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");

        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];
        echo "<img src='".url("pay/qrCode", ["data"=>$url2])."'>";
    }

    public function qrCode() {
        $url = urldecode($this->request->param('data', ''));
        if (substr($url, 0, 6) == 'weixin') {
            QRcode::png($url);
        } else {
            header('HTTP/1.1 404 Not Found');
        }
    }

    public function weixin() {
        $params = input("param.");
        //验证数据

        try {
            $result = (new \app\common\business\Pay())->unifiedOrder('weixin', $params);
        }catch (\Exception $e) {
            return Show::error($e->getMessage());
        }
        if(!$result) {
            return Show::error("下单失败");
        }
        return Show::success($result);
    }
    

    public function getPayStatus($id = 0) {
        $skuId = intval($id);
        if ($skuId <= 0) {
            return Show::error('参数错误');
        }
        $orderStatus = Cache::store('redis')->hget(config('pay.pay_status_key'), $id);
        if (!$orderStatus) {
            //去数据库查询
            if ($orderStatus = (new \app\common\model\mysql\Order())->where('order_id', $id)->find()){
                if ($orderStatus['status'] != 1) {
                    return Show::error('未支付');
                }
            }
            return Show::success('已支付');
        } else {
            $orderStatus = json_decode($orderStatus, true);
            if ($orderStatus['pay_status'] == 1) {
                return Show::success('支付成功');
            }
            return Show::error('未支付');
        }

        return Show::error('未支付');
    }
}